<template>
  <div class="hello-container">
    <!-- 添加: Header 组件 -->
    <Headers />

    <div class="content">
      <h1>选择图片</h1>
      <!-- 修改: 美化 .world 和 .docx 文件上传按钮 -->
      <label class="custom-file-upload">
        <input type="file" @change="handleFileUpload" accept=".world,.docx" />
        选择 .world 或 .docx 文件
      </label>
      <!-- 修改: 美化图片文件上传按钮 -->
      <label class="custom-file-upload">
        <input type="file" @change="handleImageUpload" accept="image/*" />
        上传图片
      </label>

      <!-- 新增: 导出按钮 -->
      <label class="custom-file-upload" @click="exportToPDF">
        导出 PDF
      </label>

      <div v-if="worldData" class="preview">
        <h2>预览内容:</h2>
        <pre>{{ worldData }}</pre>
      </div>
      <!-- 添加: overlay 容器，用于展示图片 -->
      <div class="overlay" :style="{ height: worldData || docxData ? 'auto' : '0' }" @dragover.prevent @drop="onDrop">
        <!-- 添加: 渲染上传的图片 -->
        <img v-if="imageUrl" :src="imageUrl" :class="['draggable-image', { selected: isSelected }]"
          @dragstart="onDragStart" @click="toggleSelection" draggable="true"
          :style="{ transform: `scale(${scale})`, transformOrigin: '0 0' }" /> <!-- 修改: 添加缩放样式 -->
        <!-- 添加: 显示图片尺寸信息 -->
        <div v-if="isSelected && imageUrl" class="size-info">
          尺寸: {{ Math.round(originalWidth * scale) }} x {{ Math.round(originalHeight * scale) }}px
        </div>
        <div v-if="docxData" class="preview" v-html="docxData"></div>
      </div>
    </div>

    <!-- 新增: 隐藏的导出容器，解决导出空白问题 -->
    <div class="export-container" style="visibility: visible; position: absolute; opacity: 0;">
      <div v-if="worldData" class="preview">
        <h2>预览内容:</h2>
        <pre>{{ worldData }}</pre>
      </div>
      <div v-if="docxData" class="preview" v-html="docxData"></div>
      <img v-if="imageUrl" :src="imageUrl" :class="['draggable-image']" :style="{ transform: `scale(${scale})`, transformOrigin: '0 0' }" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
const mammoth = import('mammoth');
import Headers from './Header.vue';
import html2pdf from 'html2pdf.js/dist/html2pdf.bundle.min.js';

// 定义数据
const worldData = ref<string | null>(null);
const docxData = ref<string | null>(null);
const imageUrl = ref<string | null>(null);
const isSelected = ref<boolean>(false); // 新增: 跟踪图片是否被选中
const scale = ref<number>(1); // 新增: 图片缩放比例

// 文件处理函数
const handleFileUpload = async (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];
  if (!file) return;

  if (file.name.endsWith('.world')) {
    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        worldData.value = JSON.parse(e.target?.result as string);
        docxData.value = null;
      } catch (error: any) {
        alert('无法解析.world文件: ' + error.message);
      }
    };
    reader.readAsText(file);
  } else if (file.name.endsWith('.docx')) {
    const arrayBuffer = await new Promise<ArrayBuffer>((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => resolve(reader.result as ArrayBuffer);
      reader.onerror = reject;
      reader.readAsArrayBuffer(file);
    });

    const mammothModule = await mammoth;
    const result = await mammothModule.convertToHtml({ arrayBuffer });
    docxData.value = result.value; // 存储 HTML 内容
    worldData.value = null;
  } else {
    alert('不支持的文件类型');
  }
};

// 图片处理函数
const handleImageUpload = (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];
  if (!file) return;

  const reader = new FileReader();
  reader.onload = (e) => {
    const imgUrl = e.target?.result as string;

    // 创建临时 canvas 用于处理图像
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');

    const img = new Image();
    img.onload = () => {
      canvas.width = img.width;
      canvas.height = img.height;
      ctx?.drawImage(img, 0, 0);

      if (ctx) {
        const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
        const data = imageData.data;

        // 遍历像素数据，将接近白色的背景设为透明
        const tolerance = 30; // 定义容差值，可以根据实际情况调整

        for (let i = 0; i < data.length; i += 4) {
          const r = data[i];
          const g = data[i + 1];
          const b = data[i + 2];

          // 检查颜色是否在白色附近的容差范围内
          if (
            r >= 255 - tolerance &&
            g >= 255 - tolerance &&
            b >= 255 - tolerance
          ) {
            data[i + 3] = 0; // 设置 alpha 通道为 0，即透明
          }
        }

        // 新增: 调整所有像素的透明度（alpha 通道）
        for (let i = 0; i < data.length; i += 4) {
          data[i + 3] = data[i + 3] * 0.9; // 将透明度设置为 50%，可以根据需要调整此值
        }

        ctx.putImageData(imageData, 0, 0);
        // 将处理后的图像赋值给 imageUrl
        imageUrl.value = canvas.toDataURL(); // 修改: 使用处理后的 canvas 数据
        console.log('Image URL:', imageUrl.value);
      }
    };

    img.src = imgUrl;
  };
  reader.readAsDataURL(file);
};

// 拖拽开始事件
const onDragStart = (event: DragEvent) => {
  if (isSelected.value && event.dataTransfer) {
    // 修改: 不再使用图片 src 作为拖拽数据，改为文档标识符
    event.dataTransfer.setData('text/plain', 'document');
  }
};

// 新增: 实时拖拽事件处理
const onDrag = (event: DragEvent) => {
  if (isSelected.value && event.pageX && event.pageY) {
    const imgElement = document.querySelector('.draggable-image') as HTMLImageElement;
    if (imgElement) {
      // 获取 overlay 容器的位置信息
      const overlayRect = imgElement.parentElement?.getBoundingClientRect();

      if (overlayRect) {
        // 计算相对于 overlay 容器的位置
        const relativeX = event.clientX - overlayRect.left;
        const relativeY = event.clientY - overlayRect.top;

        // 设置图片位置，保持图片中心与鼠标位置一致
        imgElement.style.position = 'absolute';
        imgElement.style.left = `${relativeX - (imgElement.offsetWidth * scale.value) / 2}px`;
        imgElement.style.top = `${relativeY - (imgElement.offsetHeight * scale.value) / 2}px`;
      }
    }
  }
};

// 新增: 更新图片位置函数
const updateImagePosition = () => {
  const imgElement = document.querySelector('.draggable-image') as HTMLImageElement;
  if (imgElement) {
    // 获取文档容器的位置
    const docContainer = document.querySelector('.preview') || document.querySelector('.hello-container');

    if (docContainer) {
      const containerRect = docContainer.getBoundingClientRect();

      // 计算图片相对于文档容器的新位置（保持在容器中心）
      const newLeft = containerRect.left + (containerRect.width - imgElement.offsetWidth * scale.value) / 2;
      const newTop = containerRect.top + (containerRect.height - imgElement.offsetHeight * scale.value) / 2;

      // 设置图片位置
      imgElement.style.position = 'absolute';
      imgElement.style.left = `${newLeft}px`;
      imgElement.style.top = `${newTop}px`;
    }
  }
};

// 修改: 拖拽释放事件
const onDrop = (event: DragEvent) => {
  if (event.dataTransfer && isSelected.value) {
    const imgElement = document.querySelector('.draggable-image') as HTMLImageElement;
    if (imgElement) {
      // 获取文档容器的位置
      const docContainer = document.querySelector('.preview') || document.querySelector('.hello-container');

      if (docContainer) {
        const containerRect = docContainer.getBoundingClientRect();

        // 计算鼠标在文档容器内的坐标
        const relativeX = event.clientX - containerRect.left;
        const relativeY = event.clientY - containerRect.top;

        // 设置图片中心点为鼠标位置
        imgElement.style.position = 'absolute';
        imgElement.style.left = `${relativeX - (imgElement.offsetWidth * scale.value) / 2}px`;
        imgElement.style.top = `${relativeY - (imgElement.offsetHeight * scale.value) / 2}px`;

        // 添加 resize 监听器来处理窗口大小变化
        window.addEventListener('resize', updateImagePosition);
      }
    }
  }
};

// 切换选中状态
const toggleSelection = () => {
  isSelected.value = !isSelected.value;
};

// 新增: 键盘事件处理函数
const handleKeyDown = (event: KeyboardEvent) => {
  if (isSelected.value && event.key === 'Delete') {
    imageUrl.value = null; // 清除图片
  }
};

// 新增: 鼠标滚轮事件处理函数
const handleWheel = (event: WheelEvent) => {
  if (isSelected.value && event.deltaY !== 0) {
    // 阻止页面滚动
    event.preventDefault();

    // 根据滚轮方向调整缩放比例
    const zoomFactor = 0.1;
    const newScale = scale.value + (event.deltaY > 0 ? -zoomFactor : zoomFactor);

    // 限制缩放范围在0.1到5之间
    if (newScale >= 0.1 && newScale <= 5) {
      scale.value = newScale;
    }
  }
};

// 新增: 导出为 PDF 函数
const exportToPDF = () => {
  const exportContainer = document.querySelector('.export-container') as HTMLElement;
  if (!exportContainer) {
    console.error("导出容器未找到");
    return;
  }

  // 修改: 增加短暂延迟确保内容加载完成
  setTimeout(() => {
    html2pdf(exportContainer, {
      margin:       1,
      filename:     'document_with_image.pdf',
      image:        { type: 'jpeg', quality: 0.98 },
      html2canvas:  { scale: 2 },
      jsPDF:        { unit: 'in', format: 'letter', orientation: 'portrait' }
    });
  }, 500); // 延迟 500ms
};

// 新增: 组件挂载后添加键盘和滚轮事件监听
onMounted(() => {
  window.addEventListener('keydown', handleKeyDown);
  window.addEventListener('drag', onDrag); // 新增: 监听全局 drag 事件
  window.addEventListener('wheel', handleWheel); // 新增: 监听鼠标滚轮事件
  window.addEventListener('resize', updateImagePosition);
});

// 新增: 组件卸载前移除键盘和滚轮事件监听
onUnmounted(() => {
  window.removeEventListener('keydown', handleKeyDown);
  window.removeEventListener('drag', onDrag); // 新增: 移除 drag 事件监听
  window.removeEventListener('wheel', handleWheel); // 新增: 移除滚轮事件监听
  window.removeEventListener('resize', updateImagePosition);
});
</script>

<style scoped>
.hello-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  width: 100vw;
}

.content {
  flex: 1;
  padding: 20px;
}

.custom-file-upload {
  display: inline-block;
  padding: 8px 16px;
  background-color: #42b983;
  color: white;
  border-radius: 4px;
  cursor: pointer;
  margin: 5px;
  z-index: 999;
}

.custom-file-upload input[type="file"] {
  display: none;
  /* 隐藏原生的文件选择框 */
}

.overlay {
  position: relative;
  width: 100%;
  min-height: 100px;
  /* 添加最小高度以便更容易看到拖放区域 */
}

.draggable-image {
  position: absolute;
  cursor: move;
  padding: 5px;
  transition: border-color 0.3s;
  will-change: transform;
  /* 保留原有优化 */
  user-select: none;
  /* 防止拖拽过程中选中文本 */
  pointer-events: auto;
  /* 确保元素响应指针事件 */
}

.draggable-image.selected {
  border-color: blue;
  outline: 2px solid blue;
}

/* 新增: 图片尺寸信息样式 */
.size-info {
  position: absolute;
  bottom: 5px;
  right: 5px;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  z-index: 2;
}

.export-container {
  visibility: visible !important; /* 强制显示 */
  opacity: 0; /* 保持不可见 */
}
</style>
